<template>
  <el-card>
    <h2>流程日志查询</h2>
    <el-form :inline="true" :model="query">
      <el-form-item label="店铺名称">
        <el-input v-model="query.storeName" placeholder="请输入店铺名称" />
      </el-form-item>
      <el-form-item label="提交类型">
        <el-select v-model="query.submitType" placeholder="请选择提交类型" style="width: 120px;" clearable>
          <el-option label="外卖" :value="1" />
          <el-option label="团购" :value="2" />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="fetchLog">查询</el-button>
        <el-button @click="fetchAllLogs">显示所有日志</el-button>
      </el-form-item>
    </el-form>

    <el-table :data="logList" style="width: 100%">
      <el-table-column prop="storeName" label="店铺名称" />
      <el-table-column label="提交人">
        <template #default="{ row }">
          {{ resolveNameByAccount(row.submitFrom) }}
        </template>
      </el-table-column>
      <el-table-column label="接收人">
        <template #default="{ row }">
          {{ resolveNameByAccount(row.submitTo) }}
        </template>
      </el-table-column>
      <el-table-column label="阶段">
        <template #default="{ row }">
          {{ getStageText(row.stage) }}
        </template>
      </el-table-column>
      <el-table-column label="外卖|团购">
        <template #default="{ row }">
          {{ row.submitType === 1 ? '外卖' : row.submitType === 2 ? '团购' : '-' }}
        </template>
      </el-table-column>
      <el-table-column prop="submitTime" label="提交时间">
        <template #default="scope">
          {{ formatDate(scope.row.submitTime) }}
        </template>
      </el-table-column>
      <el-table-column prop="remark" label="备注" />
    </el-table>
  </el-card>
</template>

<script setup>
import { ref, onMounted } from 'vue';
import { ElMessage } from 'element-plus';

const query = ref({ storeName: '', submitType: '' });
const logList = ref([]);
// 账号到姓名、员工ID到姓名的映射表
const accountNameMap = ref({});
const idNameMap = ref({});

function formatDate(dateStr) {
  if (!dateStr) return '';
  const date = new Date(dateStr);
  const y = date.getFullYear();
  const m = String(date.getMonth() + 1).padStart(2, '0');
  const d = String(date.getDate()).padStart(2, '0');
  const h = String(date.getHours()).padStart(2, '0');
  const min = String(date.getMinutes()).padStart(2, '0');
  const s = String(date.getSeconds()).padStart(2, '0');
  return `${y}-${m}-${d} ${h}:${min}:${s}`;
}

function getStageText(stage) {
  const stageStr = String(stage);
  switch (stageStr) {
    case '1':
      return '加盟提交阶段';
    case '2':
      return '证件收集提交阶段';
    case '3':
      return '团购基础配置提交阶段';
    case '4':
      return '外卖基础配置提交阶段';
    case '5':
      return '确认开业阶段';
    case '6':
      return '老店管理提交阶段';
    case '7':
      return '闭店阶段';
    default:
      return stageStr || '-';
  }
}

async function fillStoreNames(logs) {
  const storeIdSet = new Set();
  logs.forEach(log => {
    if (log.storeId) storeIdSet.add(log.storeId);
  });
  const storeIdArr = Array.from(storeIdSet);
  const storeMap = {};

  await Promise.all(storeIdArr.map(async (storeId) => {
    const res = await fetch(`http://121.43.176.9:8090/api/store/detail/${storeId}`).then(r => r.json());
    if (res.code === 200 && res.data) {
      storeMap[storeId] = res.data.storeName || '-';
    } else {
      storeMap[storeId] = '-';
    }
  }));

  logs.forEach(log => {
    log.storeName = storeMap[log.storeId] || '-';
  });
}

async function fetchLog() {
  const queryParams = new URLSearchParams();
  if (query.value.storeName) {
    queryParams.append('storeName', query.value.storeName);
  }
  if (query.value.submitType) {
    queryParams.append('submitType', query.value.submitType);
  }

  const url = `http://121.43.176.9:8090/api/log/queryByStoreName?${queryParams.toString()}`;

  try {
    const res = await fetch(url).then(r => r.json());
    if (res.code === 200) {
      const flatLogs = [];
      (res.data || []).forEach(item => {
        const store = item.store || {};
        (item.logs || []).forEach(log => {
          flatLogs.push({
            ...log,
            storeName: store.storeName || '-',
            franchisee: store.franchisee,
            phone: store.phone,
            province: store.province,
            address: store.address,
          });
        });
      });
      logList.value = flatLogs.sort((a, b) => new Date(b.submitTime) - new Date(a.submitTime));
      ElMessage.success(`共加载 ${flatLogs.length} 条日志`);
    } else {
      ElMessage.error(res.msg || '查询失败');
    }
  } catch (err) {
    ElMessage.error('请求失败: ' + err.message);
  }
}

async function fetchAllLogs() {
  try {
    const res = await fetch('http://121.43.176.9:8090/api/log/list').then(r => r.json());
    if (res.code === 200) {
      const logs = res.data || [];
      await fillStoreNames(logs);
      logList.value = logs.sort((a, b) => new Date(b.submitTime) - new Date(a.submitTime));
      ElMessage.success('已加载所有日志');
    } else {
      ElMessage.error(res.msg || '查询失败');
    }
  } catch (error) {
    ElMessage.error('查询失败: ' + error.message);
  }
}

// 通过后端接口获取员工账号与姓名、员工ID与姓名
async function loadEmployeeMaps() {
  try {
    const res = await fetch('http://121.43.176.9:8090/api/admin/all-accounts').then(r => r.json());
    if (res.code === 200) {
      const map = {};
      const employees = (res.data && res.data.employees) || [];
      employees.forEach(e => {
        if (e.account) map[e.account] = e.name || e.account;
      });
      accountNameMap.value = map;
    }
  } catch (e) {
    // 忽略错误，使用账号回退显示
  }

  // 加载包含 employeeId 的列表，构建 id -> name 和补充 account -> name
  const endpoints = [
    'http://121.43.176.9:8090/api/employee/employee0-list',
    'http://121.43.176.9:8090/api/employee/employee1-list',
    'http://121.43.176.9:8090/api/employee/type1/list',
    'http://121.43.176.9:8090/api/employee/type2/list',
    'http://121.43.176.9:8090/api/employee/employee4-list',
    'http://121.43.176.9:8090/api/employee/employee5-list',
  ];

  try {
    const results = await Promise.allSettled(endpoints.map(u => fetch(u).then(r => r.json())));
    const idMap = { ...idNameMap.value };
    const accMap = { ...accountNameMap.value };
    results.forEach(r => {
      if (r.status === 'fulfilled' && r.value && r.value.code === 200) {
        const list = r.value.data || [];
        list.forEach(emp => {
          const id = emp.employeeId || emp.employee_id;
          const name = emp.name || emp.username || emp.account;
          const account = emp.account;
          if (id != null) idMap[id] = name;
          if (account) accMap[account] = name;
        });
      }
    });
    idNameMap.value = idMap;
    accountNameMap.value = accMap;
  } catch (_) {
    // 忽略，保持已收集到的映射
  }
}

function resolveNameByAccount(value) {
  if (!value && value !== 0) return '-';
  const raw = String(value).trim();

  // 处理形如 "id:name" 或 "id:" 的情况
  if (raw.includes(':')) {
    const [firstRaw, secondRaw = ''] = raw.split(':', 2);
    const first = firstRaw.trim();
    const second = secondRaw.trim();

    // second 有内容时优先用解析出的 ID/账号映射，否则用 second
    const firstNum = Number(first);
    if (!Number.isNaN(firstNum) && idNameMap.value[firstNum]) return idNameMap.value[firstNum];
    if (accountNameMap.value[first]) return accountNameMap.value[first];
    if (second) return second;
    return first; // 只有 "id:" 时，回退用前半段
  }

  const isDigits = /^\d+$/.test(raw);
  if (isDigits) {
    const id = Number(raw);
    if (idNameMap.value[id]) return idNameMap.value[id];
    if (accountNameMap.value[raw]) return accountNameMap.value[raw];
    return raw;
  } else {
    if (accountNameMap.value[raw]) return accountNameMap.value[raw];
    const maybeId = Number(raw);
    if (!Number.isNaN(maybeId) && idNameMap.value[maybeId]) return idNameMap.value[maybeId];
    return raw;
  }
}

onMounted(() => {
  // 先加载员工映射，再加载日志
  loadEmployeeMaps().finally(() => {
    fetchAllLogs();
  });
});
</script>
